import pandas as pd
import plotly.express as px
from nicegui import ui
import os
import numpy as np


# 数据加载与预处理模块
def load_agriculture_data():
    """加载农业数据集并进行预处理"""
    try:
        # 从 CSV 文件加载数据
        df = pd.read_csv(r"C:\Users\86188\Desktop\rain-agriculture.csv")

        # 数据清洗：处理缺失值
        missing_values = df.isnull().sum()
        print(f"缺失值统计:\n{missing_values}")

        # 对缺失值进行填充（使用推荐方式）
        numeric_cols = df.select_dtypes(include=[np.number]).columns
        for col in numeric_cols:
            df.fillna({col: df[col].median()}, inplace=True)

        categorical_cols = df.select_dtypes(include=['object']).columns
        for col in categorical_cols:
            df.fillna({col: df[col].mode()[0]}, inplace=True)

        print("数据预处理完成")
        return df
    except Exception as e:
        print(f"数据加载失败: {str(e)}")
        ui.notify(f"数据加载失败: {str(e)}", type='negative')
        return None


# 数据分析模块
def analyze_agriculture_data(df):
    """分析农业数据，提取关键特征"""
    if df is None:
        return None

    # 按州名和年份分组统计
    group_stats = df.groupby(['State Name', 'Year']).agg(
        avg_rice_area=('RICE AREA (1000 ha)', 'mean'),
        avg_rice_production=('RICE PRODUCTION (1000 tons)', 'mean'),
        avg_rice_yield=('RICE YIELD (Kg per ha)', 'mean'),
        avg_jun_data=('JUN', 'mean'),
        avg_jul_data=('JUL', 'mean'),
        avg_aug_data=('AUG', 'mean'),
        avg_sep_data=('SEP', 'mean')
    ).reset_index()

    return group_stats


# 可视化模块
def create_agriculture_visualizations(df, group_stats):
    """创建农业数据可视化图表"""
    if df is None or group_stats is None:
        return None, None, None

    # 1. 不同州水稻种植面积分布饼图
    state_rice_area = df.groupby('State Name')['RICE AREA (1000 ha)'].sum()
    fig_pie = px.pie(
        state_rice_area,
        values=state_rice_area.values,
        names=state_rice_area.index,
        title='不同州水稻种植面积分布',
        labels={'value': '水稻种植面积（千公顷）', 'names': '州名'}
    )
    fig_pie.update_layout(height=500)

    # 2. 不同州平均水稻产量对比柱状图
    bar_data = group_stats.groupby('State Name')['avg_rice_production'].mean().reset_index()
    fig_bar = px.bar(
        bar_data,
        x='State Name',
        y='avg_rice_production',
        title='不同州平均水稻产量对比',
        labels={'avg_rice_production': '平均水稻产量（千吨）'},
        color='State Name'
    )
    fig_bar.update_layout(height=500)

    # 3. 水稻产量与 6 - 9 月数据关系散点图
    fig_scatter = px.scatter(
        df,
        x='RICE PRODUCTION (1000 tons)',
        y=['JUN', 'JUL', 'AUG', 'SEP'],
        color='State Name',
        title='水稻产量与 6 - 9 月数据关系',
        labels={
            'RICE PRODUCTION (1000 tons)': '水稻产量（千吨）',
            'value': '6 - 9 月数据值'
        },
        hover_data=['RICE AREA (1000 ha)', 'RICE YIELD (Kg per ha)']
    )
    fig_scatter.update_layout(height=500)

    return fig_pie, fig_bar, fig_scatter


# NiceGUI 界面模块
def build_agriculture_analysis_ui():
    """构建农业数据分析系统的 Web 界面"""
    # 加载数据
    df = load_agriculture_data()
    group_stats = analyze_agriculture_data(df)
    fig_pie, fig_bar, fig_scatter = create_agriculture_visualizations(df, group_stats)

    if df is None or group_stats is None or fig_pie is None:
        ui.notify("数据加载或处理失败，请检查数据文件", type='negative')
        return

    # 创建界面
    with ui.header(elevated=True).classes('bg-green-600 text-white'):
        ui.label('农业数据分析与可视化系统').classes('text-2xl font-bold')

    with ui.tabs().classes('w-full') as tabs:
        with ui.tab('种植面积分布', icon='pie_chart'):
            pass
        with ui.tab('水稻产量对比', icon='bar_chart'):
            pass
        with ui.tab('数据关系', icon='scatter_plot'):
            pass
        with ui.tab('数据详情', icon='table'):
            pass

    with ui.tab_panels(tabs, value='种植面积分布').classes('w-full h-[70vh]'):
        with ui.tab_panel('种植面积分布'):
            ui.plotly(fig_pie).classes('w-full h-full')

        with ui.tab_panel('水稻产量对比'):
            ui.plotly(fig_bar).classes('w-full h-full')

        with ui.tab_panel('数据关系'):
            ui.plotly(fig_scatter).classes('w-full h-full')

        with ui.tab_panel('数据详情'):
            with ui.card().classes('w-full h-full'):
                ui.label('原始数据预览 (前 20 行)').classes('text-xl font-bold mb-4')
                ui.table.from_pandas(df.head(20)).classes('w-full')

    # 数据统计信息卡片
    with ui.card().classes('w-full grid grid-cols-2 md:grid-cols-4 gap-4 p-4'):
        if 'State Name' in df.columns:
            for state in df['State Name'].unique():
                count = df[df['State Name'] == state].shape[0]
                percentage = round(count / df.shape[0] * 100, 2)
                with ui.card().classes('bg-green-100 rounded-lg p-4 items-center'):
                    ui.label(f'{state}数据数量').classes('text-gray-600')
                    ui.label(str(count)).classes('text-2xl font-bold text-green-600')
                    ui.label(f'{percentage}%').classes('text-sm text-gray-600')

    # 功能按钮区
    with ui.row().classes('w-full justify-center mt-4 gap-4'):
        ui.button('刷新数据', on_click=lambda: ui.notify('请重新运行程序刷新数据', type='info'), icon='refresh')
        ui.button('下载分析报告', on_click=lambda: ui.notify('报告下载功能开发中', type='warning'), icon='download')


# 主函数
def main():
    """主函数，启动应用"""
    build_agriculture_analysis_ui()
    ui.run(title='农业数据分析系统', port=8080, reload=False)


if __name__ == "__main__":
    main()